/**
 * @name CheckList
 * @author darcrand
 * @desc 多项列表
 */

import React, { Component } from 'react'
import './styles.scss'

class CheckList extends Component {
    static defaultProps = {
        title: '水果',
        options: [
            { label: '苹果', val: '1' },
            { label: '西瓜', val: '2' },
            { label: '桃子', val: '3' },
            { label: '哈密瓜', val: '4' }
        ],
        onChange: checkedOptions => {
            console.log('changed', checkedOptions)
        }
    }

    state = {
        isOpen: true,
        list: this.props.options.map(v => ({ ...v, checked: false }))
    }

    onTitleClick = () => {
        this.setState(pre => ({ isOpen: !pre.isOpen }))
    }

    onOptionClick = index => {
        const list = this.state.list.map((v, i) => {
            return i === index ? { ...v, checked: !v.checked } : v
        })
        this.setState({ list })
        this.props.onChange(
            list.filter(v => v.checked).map(v => {
                const opt = { ...v }
                delete opt['checked']
                return opt
            })
        )
    }

    render() {
        const { title } = this.props
        const { isOpen, list } = this.state

        return (
            <div classes="container">
                <p classes={isOpen ? 'title-open' : 'title-close'} onClick={this.onTitleClick}>
                    {title}
                </p>
                {isOpen && (
                    <ul classes="list">
                        {list.map((v, i) => (
                            <li
                                key={i}
                                classes={v.checked ? 'item-checked' : 'item-normal'}
                                onClick={() => this.onOptionClick(i)}
                            >
                                {v.label}
                            </li>
                        ))}
                    </ul>
                )}
            </div>
        )
    }
}

export default CheckList
